"""
追踪相关Pydantic模式
"""
from datetime import datetime
from typing import Optional, List
from decimal import Decimal
from pydantic import BaseModel, Field, validator

from .base import BaseSchema, TimestampSchema


class TrackingDeviceBase(BaseModel):
    """追踪设备基础模式"""
    device_id: str = Field(..., max_length=100, description="设备ID")
    device_type: str = Field(default="gps", max_length=20, description="设备类型")
    brand: Optional[str] = Field(None, max_length=100, description="品牌")
    model: Optional[str] = Field(None, max_length=100, description="型号")
    status: str = Field(default="active", max_length=20, description="状态")
    battery_level: Optional[int] = Field(None, ge=0, le=100, description="电池电量(%)")
    signal_strength: Optional[int] = Field(None, ge=0, le=100, description="信号强度")
    update_interval: int = Field(default=60, ge=1, description="更新间隔(秒)")
    cargo_id: Optional[int] = Field(None, description="关联货物ID")
    equipment_id: Optional[int] = Field(None, description="关联装备ID")


class TrackingDeviceCreate(TrackingDeviceBase):
    """创建追踪设备模式"""
    
    @validator('device_id')
    def validate_device_id(cls, v):
        if not v or len(v.strip()) == 0:
            raise ValueError('设备ID不能为空')
        return v.strip().upper()


class TrackingDeviceUpdate(BaseModel):
    """更新追踪设备模式"""
    device_type: Optional[str] = Field(None, max_length=20, description="设备类型")
    brand: Optional[str] = Field(None, max_length=100, description="品牌")
    model: Optional[str] = Field(None, max_length=100, description="型号")
    status: Optional[str] = Field(None, max_length=20, description="状态")
    battery_level: Optional[int] = Field(None, ge=0, le=100, description="电池电量(%)")
    signal_strength: Optional[int] = Field(None, ge=0, le=100, description="信号强度")
    update_interval: Optional[int] = Field(None, ge=1, description="更新间隔(秒)")
    cargo_id: Optional[int] = Field(None, description="关联货物ID")
    equipment_id: Optional[int] = Field(None, description="关联装备ID")


class TrackingDeviceResponse(TrackingDeviceBase, TimestampSchema):
    """追踪设备响应模式"""
    id: int = Field(..., description="设备ID")


class LocationHistoryBase(BaseModel):
    """位置历史基础模式"""
    device_id: int = Field(..., description="追踪设备ID")
    latitude: Decimal = Field(..., description="纬度")
    longitude: Decimal = Field(..., description="经度")
    altitude: Optional[Decimal] = Field(None, description="海拔(m)")
    accuracy: Optional[Decimal] = Field(None, description="精度(m)")
    speed: Optional[Decimal] = Field(None, ge=0, description="速度(km/h)")
    direction: Optional[Decimal] = Field(None, ge=0, le=360, description="方向(度)")
    address: Optional[str] = Field(None, max_length=500, description="地址")
    country: Optional[str] = Field(None, max_length=100, description="国家")
    province: Optional[str] = Field(None, max_length=100, description="省份")
    city: Optional[str] = Field(None, max_length=100, description="城市")
    recorded_at: datetime = Field(..., description="记录时间")


class LocationHistoryCreate(LocationHistoryBase):
    """创建位置历史模式"""
    
    @validator('latitude')
    def validate_latitude(cls, v):
        if v < -90 or v > 90:
            raise ValueError('纬度必须在-90到90之间')
        return v
    
    @validator('longitude')
    def validate_longitude(cls, v):
        if v < -180 or v > 180:
            raise ValueError('经度必须在-180到180之间')
        return v


class LocationHistoryResponse(LocationHistoryBase, TimestampSchema):
    """位置历史响应模式"""
    id: int = Field(..., description="记录ID")


class GeofenceAreaBase(BaseModel):
    """地理围栏区域基础模式"""
    name: str = Field(..., max_length=200, description="围栏名称")
    description: Optional[str] = Field(None, description="围栏描述")
    fence_type: str = Field(default="circle", max_length=20, description="围栏类型")
    center_latitude: Optional[Decimal] = Field(None, description="中心纬度")
    center_longitude: Optional[Decimal] = Field(None, description="中心经度")
    radius: Optional[Decimal] = Field(None, ge=0, description="半径(m)")
    polygon_points: Optional[dict] = Field(None, description="多边形顶点坐标")
    rule_type: str = Field(default="enter", max_length=20, description="规则类型")
    is_enabled: bool = Field(default=True, description="是否启用")


class GeofenceAreaCreate(GeofenceAreaBase):
    """创建地理围栏区域模式"""
    
    @validator('center_latitude')
    def validate_center_latitude(cls, v):
        if v is not None and (v < -90 or v > 90):
            raise ValueError('中心纬度必须在-90到90之间')
        return v
    
    @validator('center_longitude')
    def validate_center_longitude(cls, v):
        if v is not None and (v < -180 or v > 180):
            raise ValueError('中心经度必须在-180到180之间')
        return v


class GeofenceAreaUpdate(BaseModel):
    """更新地理围栏区域模式"""
    name: Optional[str] = Field(None, max_length=200, description="围栏名称")
    description: Optional[str] = Field(None, description="围栏描述")
    center_latitude: Optional[Decimal] = Field(None, description="中心纬度")
    center_longitude: Optional[Decimal] = Field(None, description="中心经度")
    radius: Optional[Decimal] = Field(None, ge=0, description="半径(m)")
    polygon_points: Optional[dict] = Field(None, description="多边形顶点坐标")
    rule_type: Optional[str] = Field(None, max_length=20, description="规则类型")
    is_enabled: Optional[bool] = Field(None, description="是否启用")


class GeofenceAreaResponse(GeofenceAreaBase, TimestampSchema):
    """地理围栏区域响应模式"""
    id: int = Field(..., description="围栏ID")


class GeofenceEventBase(BaseModel):
    """地理围栏事件基础模式"""
    device_id: int = Field(..., description="追踪设备ID")
    geofence_id: int = Field(..., description="地理围栏ID")
    event_type: str = Field(..., max_length=20, description="事件类型")
    latitude: Decimal = Field(..., description="纬度")
    longitude: Decimal = Field(..., description="经度")
    occurred_at: datetime = Field(..., description="发生时间")
    is_processed: bool = Field(default=False, description="是否已处理")
    processed_at: Optional[datetime] = Field(None, description="处理时间")


class GeofenceEventCreate(GeofenceEventBase):
    """创建地理围栏事件模式"""
    pass


class GeofenceEventResponse(GeofenceEventBase, TimestampSchema):
    """地理围栏事件响应模式"""
    id: int = Field(..., description="事件ID")


class TrackingListResponse(BaseModel):
    """追踪列表响应模式"""
    items: List[TrackingDeviceResponse] = Field(..., description="追踪设备列表")
    total: int = Field(..., description="总数量")
    page: int = Field(..., description="当前页码")
    size: int = Field(..., description="每页数量")
    pages: int = Field(..., description="总页数")


class LocationListResponse(BaseModel):
    """位置列表响应模式"""
    items: List[LocationHistoryResponse] = Field(..., description="位置历史列表")
    total: int = Field(..., description="总数量")
    page: int = Field(..., description="当前页码")
    size: int = Field(..., description="每页数量")
    pages: int = Field(..., description="总页数")


class RealTimeLocationResponse(BaseModel):
    """实时位置响应模式"""
    device_id: str = Field(..., description="设备ID")
    device_type: str = Field(..., description="设备类型")
    latitude: Decimal = Field(..., description="纬度")
    longitude: Decimal = Field(..., description="经度")
    altitude: Optional[Decimal] = Field(None, description="海拔(m)")
    speed: Optional[Decimal] = Field(None, description="速度(km/h)")
    direction: Optional[Decimal] = Field(None, description="方向(度)")
    address: Optional[str] = Field(None, description="地址")
    battery_level: Optional[int] = Field(None, description="电池电量(%)")
    signal_strength: Optional[int] = Field(None, description="信号强度")
    last_update: datetime = Field(..., description="最后更新时间")
    cargo_info: Optional[dict] = Field(None, description="关联货物信息")
    equipment_info: Optional[dict] = Field(None, description="关联装备信息")
